package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.converter.PayConverter;
import com.cskaoyan.wordmemorize.dao.entity.*;
import com.cskaoyan.wordmemorize.dao.mapper.*;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.app.PayOrderDTO;
import com.cskaoyan.wordmemorize.dto.app.VocPaySaleDTO;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.PaySuccessNotifyCommand;
import com.cskaoyan.wordmemorize.request.VocPaySaleCommand;
import com.cskaoyan.wordmemorize.service.UserPayService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserPayServiceImpl extends ServiceImpl<VocPaySaleMapper, VocPaySaleDO> implements UserPayService {
    @Resource
    VocPaySaleMapper vocPaySaleMapper;

    @Resource
    PayConverter payConverter;

    @Resource
    UserMapper userMapper;

    @Resource
    GoodsMapper goodsMapper;

    @Resource
    UserVocBoundLogMapper userVocBoundLogMapper;

    /**
     * 购买单词上限
     *
     * @param command
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public PayOrderDTO pay(VocPaySaleCommand command, Long userId) {


        // 1 保存订单信息
        VocPaySaleDO vocPaySaleDO = payConverter.vocPaySaleCommand2DO(command);

        // 判断是不是购买补签卡
        // 购买补签卡 需要去user表查询是否有补签卡  有的话抛出异常

        vocPaySaleDO.setUserId(userId);
        if (vocPaySaleDO.getItemId() == 3) {
            UserDO userDO = userMapper.selectById(userId);
            if (userDO.getHasSignCard() > 0) {
                // 返回不带支付订单id的payOrderDTO
                return payConverter.vocPaySaleDO2PayOrderDTO(vocPaySaleDO);
            }
        }

        vocPaySaleDO.setUserId(userId);
        vocPaySaleDO.setStatus(1);   // 1 表示初始化  2 表示已支付
        vocPaySaleMapper.insert(vocPaySaleDO);

        // 2 返回本次交易id
        if (vocPaySaleDO.getId() != null) {
            return payConverter.vocPaySaleDO2PayOrderDTO(vocPaySaleDO);
        } else {
            // 订单保存失败
            throw new BusinessException(ResultCodeEnum.FAIL);
        }


    }

    /**
     * 处理接收到支付成功消息
     *
     * @param command
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public String paySuccess(PaySuccessNotifyCommand command, Long userId) {

        String tradeStatus = command.getTradeStatus();

        VocPaySaleDO vocPaySaleDO = vocPaySaleMapper.selectById(command.getId());

        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            UpdateWrapper<VocPaySaleDO> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", command.getId()).set("status", 2);
            // 1. 修改订单状态
            vocPaySaleMapper.update(wrapper);
            // 查询商品信息
            GoodsDO goodsDO = goodsMapper.selectById(vocPaySaleDO.getItemId());
            // 2. 如果是补签卡  去用户表中修改补签卡数量

            if (vocPaySaleDO.getItemType() == 3) {
                UpdateWrapper<UserDO> userDOUpdateWrapper = new UpdateWrapper<>();
                userDOUpdateWrapper.eq("id", userId)
                        .setSql("has_sign_card = has_sign_card + 1");
                userMapper.update(userDOUpdateWrapper);
            } else if (vocPaySaleDO.getItemType() == 1) {
                // type = 1  修改单词上限
                // 修改voc_bound_statistics，并且向voc_bound_log中新增一条单词上限变更记录
                // 商品信息在goods表


                Integer value = goodsDO.getValue();

                vocPaySaleMapper.updateVocBoundStatistics(userId, value);

                //插入修改记录
                UserVocBoundLogDO build = UserVocBoundLogDO.builder().userId(userId)
                        .type(goodsDO.getType())
                        .logDate(LocalDate.now())
                        .count(value)
                        .description(goodsDO.getDesc())
                        .build();

                userVocBoundLogMapper.insert(build);


            } else if (vocPaySaleDO.getItemType() == 2) {
                // type = 2  等级解锁    则修改用户的等级，以及升级时间(修改user表)
                UpdateWrapper<UserDO> userDOUpdateWrapper = new UpdateWrapper<>();
                String LevelName = "LVL" + goodsDO.getValue();
                userDOUpdateWrapper.set("level_value", goodsDO.getValue())
                        .set("updated_time", LocalDateTime.now())
                        .set("level_name", LevelName)
                        .eq("id", userId);
                userMapper.update(userDOUpdateWrapper);
            }


        }

        return tradeStatus;
    }

    @Override
    public Integer queryTradeStatus(Long paySaleId) {

        VocPaySaleDO vocPaySaleDO = vocPaySaleMapper.selectById(paySaleId);

        return vocPaySaleDO.getStatus();
    }

    /**
     * 获取用户支付记录    前端暂未提供分页数据 暂不考虑分页
     *
     * @param userId
     * @param pageRequest
     * @return
     */
    @Override
    public PageDTO<VocPaySaleDTO> getPaySaleHistory(Long userId, PageRequest pageRequest) {

        LambdaQueryWrapper<VocPaySaleDO> payWrapper = new LambdaQueryWrapper<>();
        payWrapper.eq(VocPaySaleDO::getUserId, userId)
                .eq(VocPaySaleDO::getStatus, 2); // 2 表示已经支付成功了

        List<VocPaySaleDO> vocPaySaleDOS = vocPaySaleMapper.selectList(payWrapper);

        return payConverter.vocPaySalePage2PageDTO(vocPaySaleDOS, (long) vocPaySaleDOS.size());

    }
}
